package com.gitee.fastmybatis.core.mapper;

import com.gitee.fastmybatis.core.EqualColumn;
import com.gitee.fastmybatis.core.query.LambdaQuery;
import com.gitee.fastmybatis.core.query.SetBlock;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 负责编辑的mapper
 *
 * @param <E> 实体类
 * @author tanghc
 */
public interface EditMapper<E> extends SaveMapper<E>, UpdateMapper<E>, DeleteMapper<E> {

    /**
     * 根据条件删除，在有逻辑删除字段的情况下，做UPDATE操作<br>
     * <pre>
     * {@literal
     * Query query = Query.lambdaUpdate(TUser.class)
     *  .set(TUser::getRemark, "被xx删除")
     *  .eq(TUser::getId, 3);
     * int i = mapper.deleteByQuery(query);
     * }
     * 对应SQL:
     * UPDATE `t_user` SET is_del=1, remark='被xx删除' WHERE id = 3 AND is_del=0
     * </pre>
     *
     * @param query 查询对象
     * @return 受影响行数
     */
    default int deleteByQuery(LambdaQuery<E> query) {
        Objects.requireNonNull(query);
        SetBlock set = query.getSet();
        EqualColumn[] equalColumnArray;
        if (!set.isEmpty()) {
            List<EqualColumn> equalColumnList = new ArrayList<>(set.size());
            set.forEach((key, value) -> {
                equalColumnList.add(EqualColumn.of(key.toString(), value));
            });
            equalColumnArray = equalColumnList.toArray(new EqualColumn[0]);
        } else {
            equalColumnArray = new EqualColumn[]{};
        }
        return deleteByQuery(query, equalColumnArray);
    }

}
